from django.db import models
from db.base_models import BaseModel
from utils.get_hash import get_hash
from db.base_manager import BaseManager
# Create your models here.


class PassportManager(BaseManager):
    def add_one_passport(self, username, password, email):
        obj = self.create_one_object(username=username, password=get_hash(password), email=email)

        obj.save()
        return obj

    def get_one_passport(self, username, password=None):
        try:
            # 根据用户名查找
            if password is None:
                obj = self.get_one_object(username=username)
            # 根据用户名和密码查找
            else:
                obj = self.get_one_object(username=username, password=get_hash(password))
        # 查不到
        except self.model.DoesNotExist:
            obj = None
        return obj


class Passport(BaseModel):
    username = models.CharField(max_length=20, verbose_name='用户名')
    password = models.CharField(max_length=40, verbose_name='密码')
    email = models.EmailField(verbose_name='邮箱地址')

    objects = PassportManager()

    class Meta:
        db_table = 's_user_account'


class AddressManager(BaseManager):
    def get_one_address(self, passport_id):
        # 根据用户id查找默认地址
        try:
            # addr = self.get(passport=passport_id, is_default= True)
            addr = self.get_one_object(passport_id=passport_id, is_default=True)
        except self.model.DoesNotExist:
            addr = None

        return addr

    def get_address_list(self, passport_id):
        # 根据用户id查找默认地址
        try:
            # addr = self.get(passport=passport_id, is_default= True)
            addr_list = self.get_object_list(filters={'passport_id': passport_id})
        except self.model.DoesNotExist:
            addr_list = None

        return addr_list

    def add_one_address(self,passport_id, recipient_name, recipient_addr,
                        recipient_phone, zip_code):
        addr = self.get_one_address(passport_id=passport_id)

        is_default = False
        if addr is None:
            is_default = True

        addr = self.create_one_object(passport_id=passport_id, recipient_name = recipient_name,
                              recipient_addr= recipient_addr, recipient_phone = recipient_phone,
                              zip_code = zip_code, is_default = is_default)

        # 保存进数据库
        addr.save()

        return addr

    
class Address(BaseModel):
    passport = models.ForeignKey('Passport', verbose_name='所属账户')
    recipient_addr = models.CharField(max_length=256, verbose_name='收件地址')
    recipient_name = models.CharField(max_length=20, verbose_name='收件人')
    recipient_phone = models.CharField(max_length=11, verbose_name='联系电话')
    zip_code = models.CharField(max_length=6, verbose_name='邮编')

    is_default = models.BooleanField(default=False, verbose_name='是否默认')

    objects = AddressManager()
    class Meta:
        db_table = 's_user_address'

